import React, { Component } from 'react';
import 'antd/dist/antd.css';//需要添加样式
import {findCourseList} from '../utils/api';
import {Button, Descriptions} from 'antd';
import { EditOutlined } from '@ant-design/icons';
import { Table, Modal,Input,InputNumber,Radio, Form } from 'antd';
import Popconfirm from "antd/es/popconfirm";

class EditableCell extends Component {
    constructor(props) {
        super(props);
        this.state= {

        }
    }
    inputNode = this.props.inputType === 'number' ? <InputNumber /> : <Input />;
    render() {
        return (
            <td {...this.props}>
                {this.props.editing ? (
                    <Form.Item
                        name={this.props.dataIndex}
                        style={{
                            margin: 0,
                        }}
                        rules={[
                            {
                                required: true,
                                message: `Please Input ${this.props.title}!`,
                            },
                        ]}
                    >
                        {this.props.inputNode}
                    </Form.Item>
                ) : (
                    this.props.children
                )}
            </td>
        );
    }
}
class EditableTable extends Component {
    constructor(props) {
        super(props);
        this.query = this.props.location.query;//传入的参数
        if (!this.query) {
            this.query = {
                class: "2017240602",
                coursename: "软件详细设计",
                term: '2020-2021第一学期',
            }
        }
        this.formRef = React.createRef();
        this.state = {
            coursename:this.query.coursename,
            class:this.query.class,
            term:this.query.term,
            username:this.props.username,
            //下面是可编辑行表格所需要的内容
            editingKey:"",
            data:[],
            columns:[
                {
                    title: '学号',
                    dataIndex: 'studentid',
                },
                {
                    title: '学生名',
                    dataIndex: 'studentname',
                },
                {
                    title: '平时成绩',
                    dataIndex: 'usual',
                    editable: true,
                },
                {
                    title: '实验成绩',
                    dataIndex: 'experiment',
                    editable: true,
                },
                {
                    title: '卷面成绩',
                    dataIndex: 'exam',
                    editable: true,
                },
                {
                    title: '最终成绩',
                    dataIndex: 'result',
                    editable: true,
                },{
                    title: 'operation',
                    dataIndex: 'operation',
                    render: (_, record) => {
                        const editable = this.isEditing(record);
                        return editable ? (
                            <span>
                                <a  href="javascript:;"
                                    onClick={() => this.save(record.key)}
                                    style={{
                                        marginRight: 8,
                                    }}>
                                  Save
                                </a>
                            <Popconfirm title="Sure to cancel?" onConfirm={this.cancel}>
                                <a>Cancel</a>
                            </Popconfirm>
                            </span>
                            ) : (
                            <a disabled={this.state.editingKey !== ''} onClick={() => this.edit(record)}>
                                Edit
                            </a>
                        );
                    },
                }]
        }
    }
    setData(originData){
        this.setState({
            data:originData,
        })
    }
    setEditingKey(editkey){
        this.setState({
            editingKey:editkey,
        })
    }
    isEditing = record => record.key === this.state.editingKey;
    edit = record => {
        this.formRef.setFieldsValue({
            studentid: '',
            studentname: '',
            usual: '',
            experiment:'',
            exam:'',
            ...record,
        });
        this.setEditingKey(record.key);
    };
    cancel = () => {
        this.setEditingKey('');
    };
    save = async key => {
        try {
            const row = await this.formRef.validateFields();
            const newData = [...this.state.data];
            const index = newData.findIndex(item => key === item.key);
            if (index > -1) {
                const item = newData[index];
                newData.splice(index, 1, { ...item, ...row });
                this.setData(newData);
                this.setEditingKey('');
            } else {
                this.setEditingKey('');
            }
        } catch (errInfo) {
            console.log('Validate Failed:', errInfo);
        }
    };
    mergedColumns = this.state.columns.map(col => {
        if (!col.editable) {
            return col;
        }

        return {
            ...col,
            onCell: record => ({
                record,
                inputType: 'number',//(col.dataIndex === 'usual'|| col.dataIndex === 'experiment' ||col.dataIndex === 'exam') ? 'number' : 'text',
                dataIndex: col.dataIndex,
                title: col.title,
                editing: this.isEditing(record),
            }),
        };
    });
    /**
     * 初始化数据
     */
    componentDidMount() {
        //测试数据
        this.setState({
            data: [{
                "_id": "5f4e1e3102e91822e86f38da",

                "studentid": "2017905655",
                "studentname": "李青翰",
                "usual": "70",
                "experiment": "80",
                "exam": "75",
                "result": "72",
                "term": "2020-2021第一学期",
                //"gradepecents": null
            }]
        })
    }
    render() {
        return (
            <div>
                <Descriptions title="选择班级">
                    <Descriptions.Item label="学期">{this.state.term}</Descriptions.Item>
                    <Descriptions.Item label="课程">{this.state.coursename}</Descriptions.Item>
                    <Descriptions.Item label="班级">{this.state.class}</Descriptions.Item>
                </Descriptions>
                <Form form={this.formRef} component={false}>
                    <Table
                        ref={this.formRef}
                        components={{
                            body: {
                                cell: <EditableCell></EditableCell>,
                            },
                        }}
                        bordered
                        dataSource={this.state.data}
                        columns={this.mergedColumns}
                        rowClassName="editable-row"
                        pagination={{
                            onChange: this.cancel,
                        }}
                    />
                </Form>
            </div>
        );
    };
}

export default EditableTable;